#! /usr/bin/env python
# coding=utf-8
import os
from optparse import *
import commands
__author__ = 'Duke'

BASE_DIR = os.getcwd()
global_config = {
    'daemonize': 'yes',
    'dir': '%s',
    'pidfile': '%s/redis.pid',
    'bind': '0.0.0.0',
    'port': '%s',
    'tcp-backlog': 0,
    'maxclients': 100000,
    'loglevel': 'notice',
    'logfile': '%s/redis.log',
    'maxmemory': '%s',
    'save': '" "',
    'appendonly': 'no',
}

cluster_config = {
    'cluster-enabled': 'yes',
    'cluster-config-file': '%s/nodes.conf',
    'cluster-node-timeout': 5000,
}

aof_config = {
    'appendonly': 'yes',
    'appendfilename': 'appendonly.aof',
    'appendfsync': 'no'
}

rdd_config = {
    'save': '%s %s'
}

bash_shell = '''
#!/bin/bash
work_dir=%s
port=%s
if [ -f $work_dir/redis.pid ]
then
pid=`head -1 $work_dir/redis.pid`
kill -9 $pid
echo $pid已经停止
else
pid=`ps -ef |grep "redis-server 0.0.0.0:$port"|grep -v grep|awk '{print $2}'`
if [ -z $pid ]
then
echo 进程不存在
exit
else
kill -9 $pid
echo $pid已经停止
fi
fi
'''


class RedisConfig(object):
    path = None
    port = 6379
    appendonly = False
    save = False
    cluster = False
    other = {}
    maxmemory = '200m'

    def __init__(self, **kwargs):
        path = kwargs.pop('path')
        if path != BASE_DIR:
            self.path = path
        else:
            self.path = BASE_DIR
        for key, value in kwargs.items():
            setattr(self, key, value)

    def __global_config(self):
        global_config['pidfile'] %= self.path
        global_config['logfile'] %= self.path
        global_config['port'] %= self.port
        global_config['dir'] %= self.path
        global_config['maxmemory'] %= self.maxmemory

    def __cluster_config(self):
        cluster_config['cluster-config-file'] %= self.path
        global_config.update(cluster_config)

    def __aof_config(self):
        global_config.update(aof_config)

    def __rdd_config(self):
        rdd_config['save'] = rdd_config['save'] % tuple(str(self.save).split(':'))
        global_config.update(rdd_config)

    def check(self):
        if self.path[0] != '/':
            raise ValueError(u'Path must be absolute!!')
        if self.save and self.appendonly:
            raise ValueError(u'Rdd mode and Appendonly mode can not coexist!')
        if self.save and (len(str(self.save).split(":")) != 2):
            raise ValueError(u'Save Config Error')

    def __make_dir(self):
        if not os.path.isdir(self.path):
            os.mkdir(self.path)

    def __save(self):
        config = open('%s/redis.conf' % self.path, 'wb+')
        for values in global_config.items():
            config.write("%s %s\n" % values)
        config.close()
        start = open('%s/start-redis' % self.path, 'wb+')
        start.write('~/redis/src/redis-server %s/redis.conf' % self.path)
        start.close()
        commands.getstatusoutput('chmod 755 %s/start-redis' % self.path)
        self.__save_stop()

    def __save_stop(self):
        stop = open('%s/stop-redis' % self.path, 'wb+')
        stop.write(bash_shell % (self.path, self.port))
        stop.close()
        commands.getstatusoutput('chmod 755 %s/stop-redis' % self.path)

    def main(self):
        self.check()
        self.__make_dir()
        self.__global_config()
        if self.save:
            self.__rdd_config()
        if self.cluster:
            self.__cluster_config()
        if self.appendonly:
            self.__aof_config()
        self.__save()


parser = OptionParser()
parser.add_option("-p", "--path", dest="path", type='string', default=BASE_DIR, help="Config File Path")
parser.add_option("-a", "--appendonly", action='store_true', dest="appendonly", default=False, help="Aof Model Enable")
parser.add_option("-s", "--save", dest="save", default=False, help="RDB Model Enable: save <seconds>:<changes>")
parser.add_option("-c", "--cluster", action='store_true', dest="cluster", default=False, help="Cluster Model Enable")
parser.add_option("-m", "--memory", dest="maxmemory", default='200m', help="Max Memory Size")
parser.add_option("-o", "--other", dest="other", type='string', default=False, help="Other Conifg")
parser.add_option("-P", "--port", dest="port", type='string', default=6379, help="Port Number")
(options, args) = parser.parse_args()
a = RedisConfig(**options.__dict__)
a.main()